import React from 'react';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useRequest } from 'ahooks';
import { apiInterceptors, getApplogoList, uploadAppLogo, } from '@/client/api';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import Image from 'next/image';
import { useTranslation } from 'react-i18next';
import { logoUrl } from '@/utils';
import { userUpdate } from '@/client/api/login';
import { ChatContext } from '@/app/chat-context';
import { cloneDeep } from 'lodash';
import { Edge } from '@antv/x6';
import { Button, Form, Input, Modal, Spin, Select, Space, message, Cascader, Radio } from 'antd';
import Icon, { SettingOutlined } from '@ant-design/icons';
import { sqlTypesObj, dataTypeEnum, DimensionMeasurementEnum } from '@/components/workbenches/hooks/type';
import { allDomain, modelCreate, modelUpdate, modelAnalysisComment } from '@/client/api/workbenches';
import WorkbenchesIcon from '@/components/workbenches/icons';
const { Option } = Select;

const isItEnabledOptions = [
  { label: '开启', value: 1 },
  { label: '关闭', value: 0 },
]
const saveCanvasModal: React.FC<{
  graph: any;
  currentItem: any;
  checkedState: any;
  form: any;
  open: boolean;
  onCancel: () => void;
  onOk: (id?: string | null) => void;
  type?: 'add' | 'edit';
}> = ({ graph, currentItem, checkedState, form, open, onCancel, onOk, type = 'add', }) => {
  const { t, i18n } = useTranslation();
  const { mode } = useContext(ChatContext);
  const [loading, setLoading] = useState(false);
  const [areaOptions, setAreaOptions] = useState<any[]>([
    { label: '民航', value: '民航' },
    { label: '机场', value: '机场' },
  ]);
  const { run: initData } = useRequest(
    async () => {
      return await allDomain();
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { code, data } = res.data || {};
        if (code == 0) {
          const result = (data || []).map((i: any) => ({
            label: i.name,
            value: i.id + '',
          }));
          return setAreaOptions(result);
        }
        return setAreaOptions([])
      },
      debounceWait: 10,
    },
  );
  useEffect(() => {
    initData();
  }, []);
  // 运行频率0:每日一次 1:每月一次   具体执行时间（01:00）
  const [runTimeOptions, setRunTimeOptions] = useState<any[]>([
    {
      value: 0,
      label: '每日一次',
      children: [
        {
          value: '00:00',
          label: '00:00',
        },
        {
          value: '01:00',
          label: '01:00',
        },
        {
          value: '02:00',
          label: '02:00',
        },
        {
          value: '03:00',
          label: '03:00',
        },
        {
          value: '04:00',
          label: '04:00',
        },
        {
          value: '05:00',
          label: '05:00',
        },
        {
          value: '06:00',
          label: '06:00',
        },
        {
          value: '07:00',
          label: '07:00',
        },
        {
          value: '08:00',
          label: '08:00',
        },
        {
          value: '09:00',
          label: '09:00',
        },
        {
          value: '10:00',
          label: '10:00',
        },
        {
          value: '11:00',
          label: '11:00',
        },
        {
          value: '12:00',
          label: '12:00',
        },
        {
          value: '13:00',
          label: '13:00',
        },
        {
          value: '14:00',
          label: '14:00',
        },
        {
          value: '15:00',
          label: '15:00',
        },
        {
          value: '16:00',
          label: '16:00',
        },
        {
          value: '17:00',
          label: '17:00',
        },
        {
          value: '18:00',
          label: '18:00',
        },
        {
          value: '19:00',
          label: '19:00',
        },
        {
          value: '20:00',
          label: '20:00',
        },
        {
          value: '21:00',
          label: '21:00',
        },
        {
          value: '22:00',
          label: '22:00',
        },
        {
          value: '23:00',
          label: '23:00',
        },
      ],
    },
    {
      value: 1,
      label: '每月一次',
      children: [
        {
          value: '0',
          label: '每月第一天',
        },
        {
          value: '1',
          label: '每月最后一天',
        },
      ],
    },
  ]);

  const [formData] = Form.useForm();
  const init = {
    isAccelerationEnabled: 1,
    runTime: [0, '00:00'],
  }
  useEffect(() => {
    const data = {
      ...init,
      ...form,
    };
    // console.log('d322332ata', form, data,)
    formData.setFieldsValue(data);
  }, [form])
  const onFinish = async () => {
    try {
      await formData.validateFields();
    } catch (err) {
      return;
    }
    const modelInfo = formData.getFieldsValue()
    if (!modelInfo.name) {
      message.error(`请输入${t('w_name')}!`);
      return
    }
    if (!modelInfo.nameEng) {
      message.error(`请输入${t('w_nameEng')}!`);
      return
    }
    if (!modelInfo.comment) {
      message.error(`请输入${t('w_explanatoryNote')}!`);
      return
    }
    // if (!modelInfo.businessDomainIds?.length) {
    //   message.error(`请选择${t('w_area')}!`);
    //   return
    // }

    setLoading(true);
    const params: any = {
      datasourceId: currentItem?.dataSourceId,//数据源id
      databaseName: currentItem.dataSourceData.name,
      name: modelInfo.name,
      nameEng: modelInfo.nameEng,
      comment: modelInfo.comment,
      status: false,//未发布
      businessDomainIds: modelInfo.businessDomainIds.join(','),
      isAccelerationEnabled: !!modelInfo.isAccelerationEnabled,//是否开启模型加速

      statisticalGranularity: '',
      polymerizationMode: '',
      metricModelTables: [],
      metricModelTableRelationships: []
    }
    if (params.isAccelerationEnabled) {
      if (modelInfo?.runTime?.[0] === '' || modelInfo?.runTime?.[0] == null ||
        modelInfo?.runTime?.[1] === '' || modelInfo?.runTime?.[1] == null
      ) {
        message.error('请选择运行时间!');
        return
      }
      params.scheduleType = modelInfo.runTime[0];//运行频率0:每日一次 1:每月一次
      params.executionTime = modelInfo.runTime[1];	//具体执行时间（01:00）:
    }
    // 统计粒度
    const tjldResult = [];
    // 聚合方式
    const jhfsResult = [];
    for (const key in checkedState) {
      if (Object.prototype.hasOwnProperty.call(checkedState, key) && key.startsWith('tjld') && checkedState[key] === true) {
        tjldResult.push(key.split('tjld-')[1]);
      }
      if (Object.prototype.hasOwnProperty.call(checkedState, key) && key.startsWith('jhfs') && checkedState[key] === true) {
        jhfsResult.push(key.split('jhfs-')[1]);
      }
    }
    params.statisticalGranularity = tjldResult.join(',');
    params.polymerizationMode = jhfsResult.join(',');

    const data = graph.current.toJSON();
    for (const i of data.cells) {
      // console.log('i', i)
      //节点连接
      if (i.shape == "edge") {
        const { join, sourceData, targetData, fields } = i.data || {};
        for (const f of fields) {
          params.metricModelTableRelationships.push({
            joinType: join,
            sourceTableUUid: sourceData,
            targetTableUUid: targetData,
            sourceColumn: f.lField,
            targetColumn: f.rField
          })
        }
      } else if (i.shape == "react-shape") {
        // 节点
        const { tableType, id, tableOrSqlOptionsCurrentInfo, dataList } = i.data || {};
        const { x, y } = i.position || {};
        const table: any = {
          tableUUid: id,
          tableType: !!Number(tableType),	//false事实表 true查询语句
          metricModelTableColumns: [],
          x,
          y,
        }
        if (tableType == 1) {
          // 查询sql
          table.querySql = tableOrSqlOptionsCurrentInfo?.querySql;
          // 查询id
          table.querySqlId = tableOrSqlOptionsCurrentInfo?.id;
        } else {
          //表名
          table.name = tableOrSqlOptionsCurrentInfo?.tableName;
          //表名描述
          table.comment = tableOrSqlOptionsCurrentInfo?.tableComment || tableOrSqlOptionsCurrentInfo?.tableName;
        }

        table.metricModelTableColumns = [];
        for (const f of dataList) {
          if (tableType == 1) {
            const filedInfo: {
              name: any;
              comment: any;
              metricType: any;
              isTimeDimension: boolean;
              enableCodeTable?: boolean;
              codeTableName?: string;
            } = {
              name: f.name,//字段名,
              comment: f.name,//字段说明
              metricType: f.metrics,//	Metrics:度量,Dimension:维度
              isTimeDimension: !!f.isTimeDimension,//是否时间维度
              enableCodeTable: !!f.enableCodeTable,
              codeTableName: f.codeTableName,
            }
            if (!filedInfo.enableCodeTable || !filedInfo.codeTableName) {
              filedInfo.enableCodeTable = false;
              filedInfo.codeTableName = '';
            }

            table.metricModelTableColumns.push(filedInfo)
          } else {
            const filedInfo: { name: any; comment: any; metricType: any; isTimeDimension: boolean; columnPrecision?: number; enableCodeTable?: boolean; codeTableName?: string; } = {
              name: f.field,//字段名,
              comment: f.name,//字段说明
              metricType: f.metrics,//	Metrics:度量,Dimension:维度
              isTimeDimension: !!f.isTimeDimension,//是否时间维度
              enableCodeTable: !!f.enableCodeTable,
              codeTableName: f.codeTableName,
            }
            if (filedInfo.metricType == DimensionMeasurementEnum.Measurement) {
              filedInfo.columnPrecision = f.columnPrecision;
            }
            if (!filedInfo.enableCodeTable || !filedInfo.codeTableName) {
              filedInfo.enableCodeTable = false;
              filedInfo.codeTableName = '';
            }
            // console.log('f', f)
            table.metricModelTableColumns.push(filedInfo);
          }

        }
        params.metricModelTables.push(table)
      }
    }
    if (currentItem?.modelInfo?.id) {
      params.id = currentItem.modelInfo.id;
      params.status = !!currentItem?.modelInfo?.status;
    }
    console.log('par34ams', params)
    // return
    let res = null;
    if (currentItem?.modelInfo?.id) {
      res = await modelUpdate(params);
    } else {
      res = await modelCreate(params);
    }
    if (res.data.code == 0) {
      onOk(res?.data?.data + '');
      message.success(res.data.msg || '创建成功!');
    } else {
      message.error(res.data.msg || '创建失败!');
    }
    setLoading(false);
    // console.log('formData', params, modelInfo, checkedState, data, formData, formData.getFieldsValue())
  };
  const modelAnalysisCommentChange = async () => {
    try {
      await formData.validateFields();
    } catch (err) {
      return;
    }
    setLoading(true);
    const modelInfo = formData.getFieldsValue()


    const params: any = {
      datasourceId: currentItem?.dataSourceId,//数据源id
      databaseName: currentItem.dataSourceData.name,
      name: modelInfo.name || '',
      nameEng: modelInfo.nameEng || '',
      // comment: modelInfo.comment,
      // status: false,//未发布
      businessDomainIds: modelInfo.businessDomainIds?.join?.(','),
      isAccelerationEnabled: !!modelInfo.isAccelerationEnabled,//是否开启模型加速

      statisticalGranularity: '',
      polymerizationMode: '',
      metricModelTables: [],
      metricModelTableRelationships: []
    }
    if (params.isAccelerationEnabled) {
      if (modelInfo?.runTime?.[0] === '' || modelInfo?.runTime?.[0] == null ||
        modelInfo?.runTime?.[1] === '' || modelInfo?.runTime?.[1] == null
      ) {

      } else {
        params.scheduleType = modelInfo.runTime[0];//运行频率0:每日一次 1:每月一次
        params.executionTime = modelInfo.runTime[1];	//具体执行时间（01:00）:
      }
    }
    // 统计粒度
    const tjldResult = [];
    // 聚合方式
    const jhfsResult = [];
    for (const key in checkedState) {
      if (Object.prototype.hasOwnProperty.call(checkedState, key) && key.startsWith('tjld') && checkedState[key] === true) {
        tjldResult.push(key.split('tjld-')[1]);
      }
      if (Object.prototype.hasOwnProperty.call(checkedState, key) && key.startsWith('jhfs') && checkedState[key] === true) {
        jhfsResult.push(key.split('jhfs-')[1]);
      }
    }
    params.statisticalGranularity = tjldResult.join(',');
    params.polymerizationMode = jhfsResult.join(',');

    const data = graph.current.toJSON();
    for (const i of data.cells) {
      // console.log('i', i)
      //节点连接
      if (i.shape == "edge") {
        const { join, sourceData, targetData, fields } = i.data || {};
        for (const f of fields) {
          params.metricModelTableRelationships.push({
            joinType: join,
            sourceTableUUid: sourceData,
            targetTableUUid: targetData,
            sourceColumn: f.lField,
            targetColumn: f.rField
          })
        }
      } else if (i.shape == "react-shape") {
        // 节点
        const { tableType, id, tableOrSqlOptionsCurrentInfo, dataList } = i.data || {};
        const { x, y } = i.position || {};
        const table: any = {
          tableUUid: id,
          tableType: !!Number(tableType),	//false事实表 true查询语句
          metricModelTableColumns: [],
          x,
          y,
        }
        if (tableType == 1) {
          // 查询sql
          table.querySql = tableOrSqlOptionsCurrentInfo.querySql;
          // 查询id
          table.querySqlId = tableOrSqlOptionsCurrentInfo.id;
        } else {
          //表名
          table.name = tableOrSqlOptionsCurrentInfo.tableName;
          //表名描述
          table.comment = tableOrSqlOptionsCurrentInfo.tableComment || tableOrSqlOptionsCurrentInfo.tableName;
        }

        table.metricModelTableColumns = [];
        for (const f of dataList) {
          if (tableType == 1) {
            const filedInfo: {
              name: any;
              comment: any;
              metricType: any;
              isTimeDimension: boolean;
              enableCodeTable?: boolean;
              codeTableName?: string;
            } = {
              name: f.name,//字段名,
              comment: f.name,//字段说明
              metricType: f.metrics,//	Metrics:度量,Dimension:维度
              isTimeDimension: !!f.isTimeDimension,//是否时间维度
              enableCodeTable: !!f.enableCodeTable,
              codeTableName: f.codeTableName,
            }
            if (!filedInfo.enableCodeTable || !filedInfo.codeTableName) {
              filedInfo.enableCodeTable = false;
              filedInfo.codeTableName = '';
            }

            table.metricModelTableColumns.push(filedInfo)
          } else {
            const filedInfo: { name: any; comment: any; metricType: any; isTimeDimension: boolean; columnPrecision?: number; enableCodeTable?: boolean; codeTableName?: string; } = {
              name: f.field,//字段名,
              comment: f.name,//字段说明
              metricType: f.metrics,//	Metrics:度量,Dimension:维度
              isTimeDimension: !!f.isTimeDimension,//是否时间维度
              enableCodeTable: !!f.enableCodeTable,
              codeTableName: f.codeTableName,
            }
            if (filedInfo.metricType == DimensionMeasurementEnum.Measurement) {
              filedInfo.columnPrecision = f.columnPrecision;
            }
            if (!filedInfo.enableCodeTable || !filedInfo.codeTableName) {
              filedInfo.enableCodeTable = false;
              filedInfo.codeTableName = '';
            }
            // console.log('f', f)
            table.metricModelTableColumns.push(filedInfo);
          }

        }
        params.metricModelTables.push(table)
      }
    }
    // if (currentItem?.modelInfo?.id) {
    //   params.id = currentItem.modelInfo.id;
    //   params.status = !!currentItem?.modelInfo?.status;
    // }
    console.log('param32s', params)
    const res = await modelAnalysisComment(params)
    if (res.data.code == 0) {
      formData.setFieldValue('comment', res.data?.data || '');
      message.success(res.data.msg || '操作成功!');
    } else {
      message.error(res.data.msg || '操作失败!');
    }
    setLoading(false);
  }
  const [isAccelerationEnabled, setIsAccelerationEnabled] = React.useState(form.isAccelerationEnabled);
  return <Modal
    title={t('save')}
    width={500}
    open={open}
    onOk={onFinish}
    onCancel={() => onCancel(form)}
    okButtonProps={{ className: 'workbenches-B620E0' }}
  >
    <Spin spinning={loading}>
      <Form labelCol={{ span: 5 }} form={formData} name="dynamic_form_complex" onFinish={onFinish} autoComplete="off">
        <div className='mb-3'>{t('w_ModelInfo')}</div>
        <Form.Item
          name="name"
          label={t('w_name')}
          required
          rules={[
            { required: true, message: `请输入${t('w_name')}!` },
            {
              pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/,
              message: '名称可包含中文、英文、数字、下划线',
            },
          ]}
        >
          <Input className='w-80 workbenches-B620E0' maxLength={30} />
        </Form.Item>
        <Form.Item
          name="nameEng"
          label={t('w_nameEng')}
          required
          rules={[
            { required: true, message: `请输入${t('w_nameEng')}!` },
            {
              pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
              message: '英文名称必须以英文开头，可包含英文、数字、下划线',
            },
          ]}
        >
          <Input className='w-80 workbenches-B620E0' maxLength={30} />
        </Form.Item>
        <Form.Item name="comment" label={t('w_explanatoryNote')} required>
          <Input className='w-80 workbenches-B620E0' maxLength={1024} suffix={
            <div className='cursor-pointer' onClick={() => modelAnalysisCommentChange()}>
              <WorkbenchesIcon type='agent' />
            </div>
          } />
        </Form.Item>
        <Form.Item name="businessDomainIds" label={t('w_area')}>
          <Select mode="multiple" options={areaOptions} className='w-80 workbenches-B620E0' />
        </Form.Item>
        <div className='mb-3'>{t('w_ModelAcceleration')}</div>
        <Form.Item name="isAccelerationEnabled" label={t('w_IsItEnabled')} required>
          <Radio.Group options={isItEnabledOptions} className='w-80 workbenches-B620E0' onChange={(e) => {
            setIsAccelerationEnabled(e.target.value)
          }} >
          </Radio.Group>
        </Form.Item>
        {isAccelerationEnabled == 1 ? (
          <Form.Item
            name="runTime"
            label={t('w_runTime')}
            required
          >
            <Cascader
              options={runTimeOptions}
              className="w-80"
            />
          </Form.Item>
        ) : null}

      </Form>
    </Spin>
  </Modal>
}
export default saveCanvasModal;